package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Override
    @Cacheable(value = "dict" ,keyGenerator = "keyGenerator")
    public List<Dict> findChildDate(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        for (Dict dict : dicts) {
            Long id1 = dict.getId();
            boolean b = this.hasChildren(id1);
            dict.setHasChildren(b);
        }
        return dicts;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = "dict";
            // 以下载方式打开
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        List<Dict> dicts = baseMapper.selectList(null);
        List<DictEeVo> collect = dicts.stream().map(item -> {
            DictEeVo vo = new DictEeVo();
            BeanUtils.copyProperties(item,vo);
            return vo;
        }).collect(Collectors.toList());
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(collect);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    @CacheEvict(value = "dict" ,allEntries = true)
    public void importData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            QueryWrapper<Dict> dic = new QueryWrapper<>();
            dic.eq("value",value);
            Dict dict = baseMapper.selectOne(dic);
            return dict.getName();
        } else {
            QueryWrapper<Dict> dic = new QueryWrapper<>();
            dic.eq("dict_code",dictCode);
            Dict dict = baseMapper.selectOne(dic);
            QueryWrapper<Dict> dicts = new QueryWrapper<>();
            dicts.eq("parent_id",dict.getId());
            dicts.eq("value",value);
            Dict dictFinal = baseMapper.selectOne(dicts);
            return dictFinal.getName();
        }

    }

    private boolean hasChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

        Integer integer = baseMapper.selectCount(wrapper);
        return integer>0;
    }
}
